﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using OrbitOne.Elmah.Logic;

namespace OrbitOne.Elmah.Presenter
{
    public class GroupedView : CompositeControl
    {
        #region Constants
        private const int PageSize = 20;
        #endregion

        #region Controls
        protected HtmlGenericControl Pager;
        protected LinkButton Previous;
        protected LinkButton Next;
        protected Label PagerText;
        protected Label ResultsFound;
        protected Repeater Records;
        #endregion

        #region Member Variables

        #endregion

        #region Properties
        public ErrorSearchFilter SearchFilter
        {
            get
            {
                var result = ViewState["ErrorSearchFilter"] as ErrorSearchFilter;

                if (ViewState["ErrorSearchFilter"] == null)
                    result = new ErrorSearchFilter();

                return result;
            }
            set
            {
                ViewState["ErrorSearchFilter"] = value;
            }
        }
        public string ResultsStringCssClass { get; set; }
        public string PagerCssClass { get; set; }
        public int CurrentPage
        {
            get
            {
                var currentPage = ViewState["GroupedViewCurrentPage"];
                if (currentPage == null)
                {
                    return 0;
                }
                return (int)currentPage;
            }
            set
            {
                ViewState["GroupedViewCurrentPage"] = value;
            }
        }
        #endregion

        #region Methods
        protected override void OnPreRender(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindItems();
            }
            base.OnPreRender(e);
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            ResultsFound = new Label();
            PagerText = new Label();

            Records = new Repeater();

            Previous = new LinkButton
                           {
                               ID = "Previous",
                               Text = "<&nbsp;&nbsp;",
                           };
            Previous.Click += Previous_Click;

            Next = new LinkButton
                       {
                           ID = "Next",
                           Text = "&nbsp;&nbsp;>"
                       };
            Next.Click += Next_Click;

            Records.ItemDataBound += Records_ItemDataBound;

            Pager = new HtmlGenericControl("div");
            Pager.Attributes.Add("class", PagerCssClass);

            Pager.Controls.Add(Previous);
            Pager.Controls.Add(PagerText);
            Pager.Controls.Add(Next);
            
            ResultsFound.CssClass = ResultsStringCssClass;

            Controls.Add(ResultsFound);
            Controls.Add(Records);
            Controls.Add(Pager);
        }
        private void Records_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Control row = null;

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (SearchFilter.ViewGroup == ErrorSearchFilter.ResultViewGroup.ListView)
                {
                    var error = e.Item.DataItem as OrbitOneElmahErrorFacade;
                    row = new ErrorSearchRow
                              {
                                  Error = error,
                                  CssClass = "row"
                              };
                }
                else
                {
                    var record = e.Item.DataItem as SearchRecord;
                    if (record != null)
                        row = new RecordSearchRow
                                  {
                                      SearchFilterQueryString = SearchFilter.ToQueryString(ErrorSearchFilter.ResultViewGroup.ListView) + record.Key,
                                      Record = record,
                                      CssClass = "row"
                                  };
                }
                if (row != null)
                    e.Item.Controls.Add(row);
            }
        }
        private void Next_Click(object sender, EventArgs e)
        {
            CurrentPage++;
            BindItems();
        }
        private void Previous_Click(object sender, EventArgs e)
        {
            CurrentPage--;
            BindItems();
        }

        public void Refresh()
        {
            EnsureChildControls();
            CurrentPage = 0;
            BindItems();
        }
        public void BindItems()
        {
            var service = new OrbitOneElmahErrorService();
            var collection = service.SearchErrors(SearchFilter, CurrentPage * PageSize, PageSize);

            if (collection.Count == 0)
            {
                ResultsFound.Text = "No results found.";
                Pager.Visible = false;
                Records.Visible = false;
            }
            else
            {
                int totalResults;
                if (SearchFilter.ViewGroup == ErrorSearchFilter.ResultViewGroup.ListView)
                {
                    totalResults = collection.SearchRecords.First().Count;
                    if (totalResults == 1)
                    {
                        Page.Response.Redirect("ErrorDetail.aspx?id=" +
                                               collection.SearchRecords.First().Errors.Select(e => e.Id).First());
                    }
                    else
                    {
                        Records.DataSource = collection.SearchRecords.First().Errors;
                    }
                }
                else
                {
                    totalResults = collection.Count;
                    Records.DataSource = collection.SearchRecords;
                }

                ResultsFound.Text = string.Format("Found {0} results.", totalResults);
                PagerText.Text = string.Format("Page {0} of {1}", CurrentPage + 1, (totalResults / PageSize) + 1);
                Pager.Visible = totalResults > PageSize;
                Records.Visible = true;
                Records.DataBind();
            }
        }
        #endregion
    }
}
